package types

import (
	. "github.com/spf13/cast"
	"regexp"
	"strings"
)

var (
	//特殊字符列表，用于html实体转换
	specialChars []string = []string{"'", "\"", "&", "<", ">"}

	//和specialChars对应的html实体
	specialEntities []string = []string{"&#39;", "&#34;", "&#38;", "&#60;", "&#62;"}

	//html对应正则表达式列表,用于匹配html标签
	htmlRegexes []string = []string{
		`<!\-\-.*\-\->`,
		`<[^>]*>`,
	}

	//需要进行反斜杠操作的字符
	slashesChars []string = []string{"\\", "'", "\"", "\000"}

	// BbCode后缀代码
	bbCodeStrReplace []string = []string{
		`[/color]`, "",
		`[/backcolor]`, "",
		`[/size]`, "",
		`[/font]`, "",
		`[/align]`, "",
		`[b]`, "",
		`[/b]`, "",
		`[s]`, "",
		`[/s]`, "",
		`[hr]`, "",
		`[/p]`, "",
		`[i=s]`, "",
		`[i]`, "",
		`[/i]`, "",
		`[u]`, "",
		`[/u]`, "",
		`[list]`, "",
		`[list=1]`, "",
		`[list=a]`, "",
		`[list=A]`, "",
		`\r\n[*]`, "",
		`[*]`, "",
		`[/list]`, "",
		`[indent]`, "",
		`[/indent]`, "",
		`[/float]`, "",
	}

	bbCodeRegexes []string = []string{
		`\[color=([#\w]+?)\]`,
		`\[color=(rgb\([\d\s,]+?\))\]`,
		`\[backcolor=([#\w]+?)\]`,
		`\[backcolor=(rgb\([\d\s,]+?\))\]`,
		`\[size=(\d{1,2}?)\]`,
		`\[size=(\d{1,2}(\.\d{1,2})?(px|pt)+?)\]`,
		`\[font=([^\[\<]+?)\]`,
		`\[align=(left|center|right)\]`,
		`\[p=(\d{1,2}|null), (\d{1,2}|null), (left|center|right)\]`,
		`\[float=left\]`,
		`\[float=right\]`,
		`\[attach\]\d{1,}\[/attach\]`,
		`\[comment\].*\[/comment\]`,
		`\{:\d{1,}_\d{1,}:\}`,
		`\[url=.*\]`,
	}
)

//将specialChars转换成对应的specialEntities里对应的实体
func SpecialCharsEncode(value interface{}) string {
	str := ToString(value)

	for i, item := range specialChars {
		str = strings.Replace(str, item, specialEntities[i], -1)
	}

	return strings.TrimSpace(str)
}

//将specialEntities里面的实体字符转换成specialChars里对应的字符
func SpecialCharsDecode(value interface{}) string {
	str := ToString(value)

	for i, item := range specialEntities {
		str = strings.Replace(str, item, specialChars[i], -1)
	}

	return strings.TrimSpace(str)
}

//过滤所有html标签,包括注释
func RemoveHTML(value interface{}) string {
	str := ToString(value)

	for _, regex := range htmlRegexes {
		str = regexp.MustCompile(regex).ReplaceAllString(str, "")
	}

	return strings.TrimSpace(str)
}

//将slashesChars列表中的字符加上反斜杠进行转义
func AddSlashes(value interface{}) string {
	str := ToString(value)

	for _, item := range slashesChars {
		str = strings.Replace(str, item, "\\"+item, -1)
	}

	return str
}

//将转义过的字符去除反斜杠
func StripSlashes(value interface{}) string {
	str := ToString(value)

	for _, item := range slashesChars {
		str = strings.Replace(str, "\\"+item, item, -1)
	}

	return str
}

// 去除discuz中简单的BBCode代码
func RemoveBbCode(value interface{}) string {
	str := ToString(value)
	s := strings.NewReplacer(bbCodeStrReplace...)
	str = s.Replace(str)

	for _, regex := range bbCodeRegexes {
		str = regexp.MustCompile(regex).ReplaceAllString(str, "")
	}

	return strings.TrimSpace(str)
}
